package com.iseastar.guojiang.newcabinet;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.amap.api.location.AMapLocation;
import com.baidu.mapapi.model.LatLng;
import com.iseastar.dianxiaosan.model.Const;
import com.iseastar.guojiang.BaseFragment;
import com.iseastar.guojiang.MainActivity;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.loc.CourierLocationService;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.ServiceTaskBackBean;
import com.iseastar.guojiang.model.ServiceTaskBean;
import com.iseastar.guojiang.newcabinet.adapter.ServiceTaskAdapter;
import com.iseastar.guojiang.util.LocationUtils;
import com.shouhuobao.station.R;
import com.shouhuobao.take.weight.MyScrollView;

import java.util.ArrayList;

import droid.frame.push.Constants;
import droid.frame.push.PushInterface;
import droid.frame.utils.android.Log;

/**
 * 主界面-tab1 <br>
 * 智能柜、快递员负责的所有智能柜列表,同城快递
 * Created by joker on 2017/12/18.
 */
public class ServiceTaskFragment extends BaseFragment implements View.OnClickListener, MyScrollView.OnScrollListener {

    // 定位相关，传递位置
//    private static BDLocation mBdLocation;
    private TextView mTaskSumTV;//今日完成的任务数量
    private TextView mTaskSumTV1;//今日完成的任务数量
    private TextView mInComeMoneyTV;//今日收益的金额
    private TextView mInComeMoneyTV1;//今日收益的金额
    private LinearLayout mUnStartTaskLayout;//未开工的布局
    private View mStartTaskLayout;//开工的布局
    private ToggleButton mAcceptTB;//是否接收新任务
    private ToggleButton mAcceptTB1;//是否接收新任务
    private TextView mAcceptTaskDesc;
    private TextView mAcceptTaskDesc1;
    private ListView mListView;
    private ServiceTaskAdapter mAdapter = null;
    private MyScrollView scrollview;
    private LinearLayout mStartTaskLL;
    private LinearLayout mTopStartTaskLL;

    private ArrayList<ServiceTaskBean> mList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startFirstLocation();
    }

    private void startFirstLocation() {
        //刚进来的时候进行定位
        showLoadingDialog("正在定位");
        Intent intent = new Intent();
        intent.setClass(getActivityContext(), CourierLocationService.class);
        intent.putExtra("msgId", MsgID.courier_home_location_data);
        getActivityContext().startService(intent);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.fragment_service_task);
        super.findViewById();
        mStartTaskLayout = findViewById(R.id.swipe_container);
        mTaskSumTV = (TextView) findViewById(R.id.today_task_num_tv);
        mInComeMoneyTV = (TextView) findViewById(R.id.today_income_money_tv);
        scrollview = (MyScrollView) findViewById(R.id.scrollview);
        scrollview.smoothScrollTo(0, 0);
        scrollview.setOnScrollListener(this);
        mStartTaskLL = (LinearLayout) findViewById(R.id.start_task_ll);
        mTopStartTaskLL = (LinearLayout) findViewById(R.id.start_task1_ll);
        //开工按钮
        findViewById(R.id.start_task_iv).setOnClickListener(this);
        //收工按钮
        findViewById(R.id.close_task_iv).setOnClickListener(this);
        mTopStartTaskLL.findViewById(R.id.close_task_iv).setOnClickListener(this);
        mAcceptTB = (ToggleButton) findViewById(R.id.accept_tb);
        mAcceptTB1 = (ToggleButton) mTopStartTaskLL.findViewById(R.id.accept_tb);
        mAcceptTB.setOnClickListener(this);
        mAcceptTB1.setOnClickListener(this);
        mAcceptTaskDesc = (TextView) findViewById(R.id.task_accept_desc_tv);
        mAcceptTaskDesc1 = (TextView) mTopStartTaskLL.findViewById(R.id.task_accept_desc_tv);
        //未开工的布局
        mUnStartTaskLayout = (LinearLayout) findViewById(R.id.unstart_task_ll);
        mTaskSumTV1 = (TextView) mUnStartTaskLayout.findViewById(R.id.today_task_num_tv);
        mInComeMoneyTV1 = (TextView) mUnStartTaskLayout.findViewById(R.id.today_income_money_tv);

        mListView = (ListView) findViewById(R.id.listview_in_scrollview);
        mAdapter = new ServiceTaskAdapter(mList, getActivityContext());
        mListView.setAdapter(mAdapter);

        mAcceptTB.setChecked(MainActivity.instance.isReceiverOrder());
        mAcceptTB1.setChecked(MainActivity.instance.isReceiverOrder());
        if (MainActivity.instance.isReceiverOrder()) {
            mAcceptTaskDesc.setText("新任务接收中,点击可关闭");
            mAcceptTaskDesc1.setText("新任务接收中,点击可关闭");
        } else {
            mAcceptTaskDesc.setText("新任务已关闭,无法接收新任务");
            mAcceptTaskDesc1.setText("新任务已关闭,无法接收新任务");
        }

        mUnStartTaskLayout.setVisibility(View.VISIBLE);
        mStartTaskLayout.setVisibility(View.GONE);
        //当布局的状态或者控件的可见性发生改变回调的接口
        findViewById(R.id.root_layout).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                //这一步很重要，使得上面的开关布局和下面的开关布局重合
                onScroll(scrollview.getScrollY());

            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ServiceTaskBean bean = (ServiceTaskBean) parent.getItemAtPosition(position);
                if (null == bean) {
                    return;
                }
                Intent intent = null;
                if (Const.CourierTaskStatus.sameCityTask == bean.getTaskType()) {
                    intent = new Intent(getActivityContext(), SameCityTaskMainActivity.class);
                } else {
                    intent = new Intent(getActivityContext(), TaskMainDetailActivity.class);
                    intent.putExtra("type", 1);
                }
                intent.putExtra("item", bean);
                startActivity(intent);
            }
        });
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (null != MainActivity.aMapLocation) {
                    showToast("刷新成功");
                    refreshTaskData();
                } else {
                    startFirstLocation();
                    showToast("刷新失败,请检查定位");
                }
            }
        });
    }


    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            // 获取位置
            case MsgID.courier_home_location_data:
                cancelLoadingDialog();
                MainActivity.aMapLocation = (AMapLocation) msg.obj;
                if (null != MainActivity.aMapLocation) {
                    showToast("获取定位成功");
                    refreshTaskData();
                } else {
                    startFirstLocation();
                    if (MainActivity.aMapLocation != null && MainActivity.aMapLocation.getErrorCode() == 4) {
                        showToast("当前网络不稳定");
                    }
                }
                return true;
            //点击开工或收工,是否开工或收工
            case MsgID.courier_start_or_close_work:
                cancelLoadingDialog();
                Log.d("33333",msg.obj);
                final ReqResult<?> startWorkResult = JSON.parser(msg.obj);
                if (checkLoginStatus(startWorkResult)) {
                    getActivityContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            boolean isWork = (Boolean) startWorkResult.getResult();
                            MainActivity.instance.setWork(isWork);
                            //如果开工并且在接单中,打开定位
                            if (MainActivity.instance.isReceiverOrder() && isWork) {
                                if (AppCache.getUser().getId() > 0) {
                                    PushInterface.init(Constants.AppType.HuoJianXia);
                                }
                                MainActivity.instance.startOrStopRefreshLocation(true);
                            } else {
                                //关闭定位,就是不接单或收工
                                MainActivity.instance.startOrStopRefreshLocation(false);
                            }
                            if (isWork) {
                                mUnStartTaskLayout.setVisibility(View.GONE);
                                mStartTaskLayout.setVisibility(View.VISIBLE);
                                mTopStartTaskLL.setVisibility(View.VISIBLE);
                                scrollview.smoothScrollTo(0, 0);
                                mAcceptTaskDesc.setText("新任务接收中,点击可关闭");
                                mAcceptTaskDesc1.setText("新任务接收中,点击可关闭");
//                                if (MainActivity.aMapLocation != null) {
//                                    showLoadingDialog(null);
//                                    refreshTaskData();
//                                }
                            } else {
                                mUnStartTaskLayout.setVisibility(View.VISIBLE);
                                mStartTaskLayout.setVisibility(View.GONE);
                                mTopStartTaskLL.setVisibility(View.GONE);
                                mAcceptTaskDesc.setText("新任务已关闭,无法接收新任务");
                                mAcceptTaskDesc1.setText("新任务已关闭,无法接收新任务");
                            }
                        }
                    });
                } else {
                    showToast(startWorkResult.getMessage());
                }
                return true;
            //选择是否接单返回
            case MsgID.courier_receiver_order:
                cancelLoadingDialog();
                final ReqResult<?> recievierOrderResult = JSON.parser(msg.obj);
                getActivityContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(recievierOrderResult)) {
                            boolean isReceiverOrder = (Boolean) recievierOrderResult.getResult();
                            MainActivity.instance.setReceiverOrder(isReceiverOrder);
                            Log.d("11111", "点击接收任务或不接受任务 isReceiverOrder：" + isReceiverOrder);
                            MainActivity.instance.startOrStopRefreshLocation(isReceiverOrder);
                            mAcceptTB.setChecked(isReceiverOrder);
                            mAcceptTB1.setChecked(isReceiverOrder);
                            if (isReceiverOrder) {
                                if (AppCache.getUser().getId() > 0) {
                                    PushInterface.init(Constants.AppType.HuoJianXia);
                                }
                                mAcceptTaskDesc.setText("新任务接收中,点击可关闭");
                                mAcceptTaskDesc1.setText("新任务接收中,点击可关闭");
                            } else {
                                mAcceptTaskDesc.setText("新任务已关闭,无法接收新任务");
                                mAcceptTaskDesc1.setText("新任务已关闭,无法接收新任务");
                            }

                        } else {
                            mAcceptTB.setChecked(MainActivity.instance.isReceiverOrder());
                            mAcceptTB1.setChecked(MainActivity.instance.isReceiverOrder());
                            if (MainActivity.instance.isReceiverOrder()) {
                                mAcceptTaskDesc.setText("新任务接收中,点击可关闭");
                                mAcceptTaskDesc1.setText("新任务接收中,点击可关闭");
                            } else {
                                mAcceptTaskDesc.setText("新任务已关闭,无法接收新任务");
                                mAcceptTaskDesc1.setText("新任务已关闭,无法接收新任务");
                            }
                            showToast(recievierOrderResult.getMessage());
                        }
                    }
                });
                return true;
            //获取首页数据
            case MsgID.get_courier_home_data:
                cancelLoadingDialog();
                onRefreshComplete();
                final ReqResult<ServiceTaskBackBean> result = JSON.parser(msg.obj, ServiceTaskBackBean.class);
                if (checkLoginStatus(result)) {
                    getActivityContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ServiceTaskBackBean backBean = result.getResult();
                            if (null != backBean) {
                                mList.clear();
                                //同城  上门  驿站  到柜 回仓
                                int normalNum = 0;//上门 驿站 到柜
                                int sameCityNum = 0;//同城的任务数量
                                if (null != backBean.getCitySend() && backBean.getCitySend().size() > 0) {
                                    sameCityNum = backBean.getCitySend().size();
                                    mList.addAll(backBean.getCitySend());
                                }
                                if (null != backBean.getDoors() && backBean.getDoors().size() > 0) {
                                    mList.addAll(backBean.getDoors());
                                    normalNum += backBean.getDoors().size();
                                }
                                if (null != backBean.getStation() && backBean.getStation().size() > 0) {
                                    normalNum += backBean.getStation().size();
                                    mList.addAll(backBean.getStation());
                                }
                                if (null != backBean.getTransfer()) {
                                    mList.add(backBean.getTransfer());
                                }
                                mAdapter.setItems(mList, sameCityNum, normalNum, backBean, true);
                                mTaskSumTV.setText(backBean.getTodayOverCnt());
                                mTaskSumTV1.setText(backBean.getTodayOverCnt());
                                mInComeMoneyTV.setText(backBean.getTodayMoney());
                                mInComeMoneyTV1.setText(backBean.getTodayMoney());
                                mAcceptTB.setChecked(backBean.getReceiverOrder());
                                mAcceptTB1.setChecked(backBean.getReceiverOrder());
                                //开工中
                                boolean isWork = backBean.getStartWork();
                                MainActivity.instance.setWork(isWork);
                                if (isWork) {
                                    mUnStartTaskLayout.setVisibility(View.GONE);
                                    mStartTaskLayout.setVisibility(View.VISIBLE);
                                    mTopStartTaskLL.setVisibility(View.VISIBLE);
                                    scrollview.smoothScrollTo(0, 0);
                                    mAcceptTaskDesc.setText("新任务接收中,点击可关闭");
                                    mAcceptTaskDesc1.setText("新任务接收中,点击可关闭");
                                } else {
                                    mUnStartTaskLayout.setVisibility(View.VISIBLE);
                                    mStartTaskLayout.setVisibility(View.GONE);
                                    mTopStartTaskLL.setVisibility(View.GONE);
                                    mAcceptTaskDesc.setText("新任务已关闭,无法接收新任务");
                                    mAcceptTaskDesc1.setText("新任务已关闭,无法接收新任务");
                                }
                                boolean isReceiverOrder = backBean.getReceiverOrder();
                                MainActivity.instance.setReceiverOrder(isReceiverOrder);
                                //如果开工并且在接单中,打开定位
                                Log.d("11111", "刚进入首页请求回来的数据：isReceiverOrder:" + isReceiverOrder + ",isWork:" + isWork);
                                if (isReceiverOrder && isWork) {
                                    MainActivity.instance.startOrStopRefreshLocation(true);
                                    if (AppCache.getUser().getId() > 0) {
                                        PushInterface.init(Constants.AppType.HuoJianXia);
                                    }
                                } else {
                                    //关闭定位,就是不接单或收工
                                    MainActivity.instance.startOrStopRefreshLocation(false);
                                }
                                mAcceptTB.setChecked(isReceiverOrder);
                                mAcceptTB1.setChecked(isReceiverOrder);
                                if (isReceiverOrder) {
                                    mAcceptTaskDesc.setText("新任务接收中,点击可关闭");
                                    mAcceptTaskDesc1.setText("新任务接收中,点击可关闭");
                                } else {
                                    mAcceptTaskDesc.setText("新任务已关闭,无法接收新任务");
                                    mAcceptTaskDesc1.setText("新任务已关闭,无法接收新任务");
                                }
                            } else {
                                showToast("数据有误");
                            }
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击开工按钮
            case R.id.start_task_iv:
                showLoadingDialog(null);
                AppHttp.getInstance().courierStartOrCloseWork(true);
                break;
            //收工按钮
            case R.id.close_task_iv:
//                if (mAdapter.getItemsSize() > 0) {
//                    showToast("当前有任务未完成");
//                    return;
//                }
                showLoadingDialog(null);
                AppHttp.getInstance().courierStartOrCloseWork(false);
                break;
            //是否接收新任务
            case R.id.accept_tb:
                mAcceptTB.setChecked(MainActivity.instance.isReceiverOrder());
                mAcceptTB1.setChecked(MainActivity.instance.isReceiverOrder());
                if (MainActivity.instance.isReceiverOrder()) {
                    mAcceptTaskDesc.setText("新任务接收中,点击可关闭");
                    mAcceptTaskDesc1.setText("新任务接收中,点击可关闭");
                } else {
                    mAcceptTaskDesc.setText("新任务已关闭,无法接收新任务");
                    mAcceptTaskDesc1.setText("新任务已关闭,无法接收新任务");
                }
                showLoadingDialog(null);
                AppHttp.getInstance().courierIsReceiverOrderork(!MainActivity.instance.isReceiverOrder());
                break;
        }
    }

    @Override
    public void onScroll(int scrollY) {
        int mBuyLayout2ParentTop = Math.max(scrollY, mStartTaskLL.getTop());
        mTopStartTaskLL.layout(0, mBuyLayout2ParentTop, mTopStartTaskLL.getWidth(), mBuyLayout2ParentTop + mTopStartTaskLL.getHeight());
    }

    /**
     * 进行刷新数据
     */
    public void refreshTaskData() {
        LatLng dPoint = LocationUtils.locationConvert(MainActivity.aMapLocation);
        if (dPoint != null) {
            Log.d("33333", "refreshTaskData()");
            AppHttp.getInstance().getCourierHomeData(dPoint.latitude, dPoint.longitude);
        }
    }


    /**
     * 如果火箭侠还有任务，调用不接收任务接口，否则调用收工接口
     */
    public void updateCourierStatus() {
        if (mAdapter != null && mAdapter.getItemsSize() > 0) {
            AppHttp.getInstance().courierIsReceiverOrderork(false);
        } else {
            AppHttp.getInstance().courierStartOrCloseWork(false);
        }
    }

}
